<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图片三次加载后默认</title>
</head>
<body>
<img src="https://www.baidu.cmo/img.png" alt="" retry="0">
<script>
    const img = document.querySelector('img')

    img.onerror = (e) => {
        handleError(img, img.getAttribute('retry'))
    }

    function handleError(El, retry) {
        retry = parseInt(retry)
        let timer = setTimeout(() => {
            if (retry > 3) {
                console.log('连接失败')
                El.src = 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'
                clearTimeout(timer)

            } else {
                console.log('重试次数', retry)
                retry += 1
                El.setAttribute('retry',retry)
                El.src = 'https://www.baidu.cmo/img.png'
            }
        }, 1500)
    }
</script>

</body>
</html>
